package com.handpay.zztong.hp.jpush;

import android.app.Notification;
import android.content.Context;
import android.content.IntentFilter;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;

import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.log.HPLog;

import java.util.Set;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import static com.handpay.zztong.hp.jpush.JPushReceiver.MESSAGE_RECEIVED_ACTION;

/**
 * @author sxshi on 2017/3/8.
 * @email:emotiona_xiaoshi@126.com
 * @describe:极光推送相关设置
 */

public class JpushManager {
    private Context mContext;
    private JPushReceiver jPushReceiver;

    public JpushManager(Context mContext) {
        this.mContext = mContext;
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    HPLog.i(HPLog.SSX_TAG, logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    HPLog.i(HPLog.SSX_TAG, logs);
                    if (JpushUtils.isConnected(mContext)) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        HPLog.i(HPLog.SSX_TAG, "No network");
                    }
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    HPLog.e(HPLog.SSX_TAG, logs);
            }
        }
    };

    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    HPLog.i(HPLog.SSX_TAG, logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    HPLog.i(HPLog.SSX_TAG, logs);
                    if (JpushUtils.isConnected(mContext)) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
                    } else {
                        HPLog.i(HPLog.SSX_TAG, "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    HPLog.e(HPLog.SSX_TAG, logs);
            }
        }

    };

    private static final int MSG_SET_ALIAS = 1001;
    private static final int MSG_SET_TAGS = 1002;

    /**
     * 自定义hander用于设置tag/别名
     */
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    HPLog.d(HPLog.SSX_TAG, "Set alias in handler.");
                    JPushInterface.setAliasAndTags(mContext, (String) msg.obj, null, mAliasCallback);
                    break;

                case MSG_SET_TAGS:
                    HPLog.d(HPLog.SSX_TAG, "Set tags in handler.");
                    JPushInterface.setAliasAndTags(mContext, null, (Set<String>) msg.obj, mTagsCallback);
                    break;
                default:
                    HPLog.i(HPLog.SSX_TAG, "Unhandled msg - " + msg.what);
            }
        }
    };

    /**
     * 设置别名
     *
     * @param alias 用户的userid
     */
    public void setAlias(String alias) {
        HPLog.d(HPLog.SSX_TAG, "alias:" + alias);
        if (TextUtils.isEmpty(alias)) {
            Toast.makeText(mContext, R.string.error_alias_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        if (!JpushUtils.isValidTagAndAlias(alias)) {
            Toast.makeText(mContext, R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show();
            return;
        }
        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    /**
     * 设置通知提示方式 - 基础属性
     */
    public void setStyleBasic() {
        BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(mContext);
        builder.statusBarDrawable = R.drawable.ic_launcher;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL;  //设置为点击后自动消失
        builder.notificationDefaults = Notification.DEFAULT_SOUND;  //设置为铃声（ Notification.DEFAULT_SOUND）或者震动（ Notification.DEFAULT_VIBRATE）
        JPushInterface.setPushNotificationBuilder(1, builder);
    }

    /**
     * 设置通知栏样式 - 定义通知栏Layout
     */
    public void setStyleCustom() {
        CustomPushNotificationBuilder builder = new CustomPushNotificationBuilder(mContext, R.layout.customer_notitfication_layout, R.id.icon, R.id.title, R.id.text);
        builder.layoutIconDrawable = R.drawable.ic_launcher;
        builder.developerArg0 = "developerArg2";
        JPushInterface.setPushNotificationBuilder(2, builder);
    }

    /**
     * 停止极光推送
     */
    public void stopJpush() {
        JPushInterface.stopPush(mContext);
    }

    /**
     * 回复极光推送
     */
    public void resumeJPush() {
        JPushInterface.resumePush(mContext);
    }

    /**
     * 设置允许推送的时间
     */
    public void setPushTime() {
        // TODO: 2017/3/8 未完成推送时间设置

    }

    /**
     * 注册自定义广播
     */
    public void registerJPushReceiver() {
        jPushReceiver = new JPushReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        mContext.registerReceiver(jPushReceiver, filter);
    }

    /**
     * 解绑广播
     */
    public void unregisterJPushReceiver() {
        mContext.unregisterReceiver(jPushReceiver);
    }
}
